package org.whb.order.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.whb.basic.service.impl.BaseServiceImpl;
import org.whb.basic.util.CodeGenerateUtils;
import org.whb.order.domain.AdoptOrder;
import org.whb.order.domain.OrderAddress;
import org.whb.order.domain.PetAcquisitionOrder;
import org.whb.order.mapper.AdoptOrderMapper;
import org.whb.order.mapper.OrderAddressMapper;
import org.whb.order.service.IAdoptOrderService;
import org.whb.pay.constants.BussinessType;
import org.whb.pay.domain.PayBill;
import org.whb.pay.mapper.PayBillMapper;
import org.whb.pay.service.IPayBillService;
import org.whb.pet.domain.Pet;
import org.whb.pet.domain.SearchMasterMsg;
import org.whb.pet.mapper.PetMapper;
import org.whb.quartz.constants.JobConstants;
import org.whb.quartz.service.IQuartzService;
import org.whb.quartz.utils.QuartzJobInfo;
import org.whb.user.domain.Logininfo;
import org.whb.user.domain.User;
import org.whb.user.domain.UserAddress;
import org.whb.user.mapper.UserAddressMapper;
import org.whb.user.mapper.UserMapper;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdoptOrderServiceImpl extends BaseServiceImpl<AdoptOrder> implements IAdoptOrderService {

    @Autowired
    private AdoptOrderMapper adoptOrderMapper;
    @Autowired
    private OrderAddressMapper orderAddressMapper;
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private UserMapper userMapper;
    @Value("${order.last.pay.time}")
    private Integer latsPayTime;
    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    private PayBillMapper payBillMapper;
    @Autowired
    private IPayBillService payBillService;
    @Autowired
    private IQuartzService quartzService;

    /**
     * 宠物领养订单
     * @param params
     * @param logininfo
     * @return
     */
    @Override
    public String submit(Map<String, Object> params, Logininfo logininfo) {
        //配送方法
        Integer serviceMethod = Integer.valueOf(params.get("service_method").toString());
        //用户的地址id
        Long addressId = Long.valueOf(params.get("address_id").toString());
        //支付方式
        Long payMethod = Long.valueOf(params.get("pay_method").toString());
        //宠物id
        Long petId = Long.valueOf(params.get("pet_id").toString());

        //领养订单中：shopid ，addressid

        //获取订单地址
        //商品下架
        Pet pet = petMapper.loadById(petId);
        pet.setState(0);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        //哪个用户买的这个产品
        pet.setUser_id(user.getId());
        pet.setOffsaletime(new Date());
        petMapper.update(pet);

        //保存订单
        AdoptOrder order = initAdoptOrder(pet, user);
        order.setPaySn(CodeGenerateUtils.generateUnionPaySn());
        adoptOrderMapper.save(order);

        //保存订单地址
        UserAddress userAddress = userAddressMapper.loadById(addressId);
        OrderAddress orderAddress = getOrderAddress(order, userAddress);
        orderAddressMapper.save(orderAddress);

        //生成支付单
        PayBill bill = initPayBill(payMethod, pet, user, order);
        payBillMapper.save(bill);

        //超时取消订单
        QuartzJobInfo info = new QuartzJobInfo();
        String jobName= JobConstants.JOB_TYPE_ADOPT_ORDER_PAY_CANCEL+order.getId();
        info.setJobName(jobName);
        Map<String ,Object> map = new HashMap<>();
        map.put("type", JobConstants.JOB_TYPE_ADOPT_ORDER_PAY_CANCEL);
        map.put("orderId", order.getId());
        info.setParams(map);
        info.setFireDate(order.getLastPayTime());

        quartzService.addJob(info);
        return payBillService.pay(bill);
    }

    @Override
    public void cancelOrder(Long orderId) {
        AdoptOrder adoptOrder = adoptOrderMapper.loadById(orderId);
        System.out.println(adoptOrder);
        if(adoptOrder!=null){
            if(adoptOrder.getState()==0){
                adoptOrder.setState(-1);
                adoptOrderMapper.update(adoptOrder);
            }
        }

    }

    private PayBill initPayBill(Long payMethod, Pet pet, User user, AdoptOrder order) {
        PayBill bill = new PayBill();
        bill.setDigest("[摘要]对:"+pet.getName()+"领养支付订单！");
        bill.setMoney(order.getPrice());
        bill.setUnionPaySn(order.getPaySn());
        bill.setState(1);
        bill.setLastPayTime(order.getLastPayTime());
        bill.setPayChannel(payMethod);
        bill.setBusinessType(BussinessType.BUSSINESS_TYPE_ALIPAY_ADOPT);
        bill.setBusinessKey(order.getId());
        bill.setUser_id(order.getUser_id());
        bill.setShop_id(order.getShop_id());
        bill.setNickName(user.getUsername());
        return bill;
    }

    private OrderAddress getOrderAddress(AdoptOrder order, UserAddress userAddress) {
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(userAddress, orderAddress);
        orderAddress.setOrderSn(order.getOrderSn());
        orderAddress.setOrder_id(order.getId());
        return orderAddress;
    }

    private AdoptOrder initAdoptOrder(Pet pet, User user) {
        AdoptOrder order = new AdoptOrder();
        order.setDigest("[摘要]对"+pet.getName()+"收购订单！");
        order.setState(0);
        order.setPrice(pet.getSaleprice());
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(user.getId()));
        order.setLastPayTime(new Date(System.currentTimeMillis()+latsPayTime));
        order.setPet_id(pet.getId());
        order.setUser_id(user.getId());
        order.setShop_id(pet.getShop_id());
        return order;
    }


}
